import { Component, OnInit } from '@angular/core';
import { RoleService } from 'src/app/service/role.service';
import { CommonService } from 'src/app/service/common.service';
import { NzMessageService } from 'ng-zorro-antd';

export interface TreeNodeInterface {
  _id: string;
  name: string;
  level: number;
  expand: boolean;
  key: string;
  father: string;
  childs?: TreeNodeInterface[];
}

@Component({
  selector: 'app-author',
  templateUrl: './author.component.html',
  styleUrls: ['./author.component.scss'],
  providers: [RoleService, CommonService]
})
export class AuthorComponent implements OnInit {
  name: any;
  total = 1;
  pageIndex = 1;
  pageSize = 15;
  dataSet = [];
  loading = true;
  doc: any = {};
  isVisible = false;
  isOkLoading = false;
  isAuthor = false;
  res: any;
  checkedItems: Array<any> = [];
  checkedItem: any;
  displayData: Array<any> = [];
  data: any = [];
  expandDataCache = {};

  collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void {
    if ($event === false) {
      if (data.childs) {
        data.childs.forEach(d => {
          const target = array.find(a => a.key === d.key);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: object): TreeNodeInterface[] {
    const stack = [];
    const array = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.childs) {
        for (let i = node.childs.length - 1; i >= 0; i--) {
          node.childs[i].select = node.childs[i].select ? node.childs[i].select : false;
          stack.push({ ...node.childs[i], level: node.level + 1, expand: false, father: node });
        }
      }
    }

    return array;
  }

  visitNode(node: TreeNodeInterface, hashMap: object, array: TreeNodeInterface[]): void {
    if (!hashMap[node.key]) {
      hashMap[node.key] = true;
      array.push(node);
    }
  }

  constructor(private roleservice: RoleService, private commonservice: CommonService, private msg: NzMessageService) { }

  ngOnInit() {
    this.searchData();
  }

  searchData() {
    this.roleservice.query().then((res) => {
      if (res) {
        this.loading = false;
        this.total = res.length;
        this.dataSet = res.map((a) => {
          a.isInternal = a.isInternal ? '是' : '否';
          return a;
        });
      }
    });
  }

  add() {
    this.isVisible = true;
  }

  edit(id) {
    this.isVisible = true;
    this.roleservice.queryById(id).then(res => {
      this.doc = res;
      this.doc.isInternal = this.doc.isInternal ? 'true' : 'false';
    });
  }

  handleOk(): void {
    this.isOkLoading = true;
    if (!this.doc.name || this.doc.name == '') {
      this.msg.warning('请填角色名称！');
    } else if (!this.doc.isInternal) {
      this.msg.warning('请选择是否内置角色！');
    } else {
      if (this.doc._id) {
        this.roleservice.update(this.doc).then((res) => {
          this.searchData();
          this.msg.success('修改成功！');
          this.isVisible = false;
          this.doc = {};
        });
      } else {
        this.roleservice.create(this.doc).then((res) => {
          this.searchData();
          this.msg.success('新增成功！');
          this.isVisible = false;
          this.doc = {};
        });
      }


    }
  }

  author(id) {
    this.isAuthor = true;
    this.roleservice.queryById(id).then(res => {
      this.data = res.menus;
      this.res = res;
      this.checkedItems = res.rights;
      this.data.forEach(item => {
        this.expandDataCache[item.key] = this.convertTreeToList(item);
      });
    });
  }

  refreshStatus(item: any): void {
    let index;
    for (let i = 0; i < this.checkedItems.length; i++) {
      if (this.checkedItems[i] === item._id) {
        index = i;
      }
    }
    if (index || index === 0) {
      this.checkedItems.splice(index, 1);
      item.select = false;
    } else {
      item.select = true;
      this.checkedItem = item;
      if (this.checkedItems.findIndex((a) => {
        return a === item._id;
      }) < 0) {
        this.checkedItems.push(item._id);
      }
    }
  }

  handleCancel(): void {
    this.isVisible = false;
    this.doc = {};
  }

  /**删除 */
  delete(id: any) {
    this.commonservice.confirm('确定要删除该条信息?', () => {
      this.roleservice.delete(id).then((res) => {
        this.msg.success('删除成功！');
        this.searchData();
      });
    });
  }

  authorCancel() {
    this.isAuthor = false;
  }

  authorOk() {
    this.res.rights = this.checkedItems;
    this.roleservice.update(this.res);
    this.isAuthor = false;
  }

}
